package com.newshub.app.ui.news

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.newshub.app.data.model.News
import com.newshub.app.data.model.NewsDetail
import com.newshub.app.data.repository.NewsRepository
import kotlinx.coroutines.launch

class NewsDetailViewModel : ViewModel() {
    
    private val newsRepository = NewsRepository
    
    private val _newsDetail = MutableLiveData<News?>(null)
    val newsDetail: LiveData<News?> = _newsDetail
    
    private val _isLoading = MutableLiveData<Boolean>(false)
    val isLoading: LiveData<Boolean> = _isLoading
    
    private val _errorMessage = MutableLiveData<String?>(null)
    val errorMessage: LiveData<String?> = _errorMessage
    
    fun loadNewsDetail(docid: String) {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _errorMessage.value = null
                
                // 从Repository获取新闻详情
                val news = newsRepository.getNewsById(docid)
                _newsDetail.value = news
                _isLoading.value = false
            } catch (e: Exception) {
                _errorMessage.value = e.message ?: "加载新闻详情失败"
                _isLoading.value = false
            }
        }
    }
    
    fun toggleFavorite(docid: String) {
        viewModelScope.launch {
            try {
                val isCurrentlyFavorite = newsRepository.isFavorite(docid)
                
                if (isCurrentlyFavorite) {
                    newsRepository.removeFromFavorite(docid)
                } else {
                    // 为了简化，我们可以根据docid创建一个简单的News对象
                    // 在实际应用中，应该从数据库获取完整的新闻对象
                    _newsDetail.value?.let {
                        newsRepository.addToFavorite(it.copy(isFavorite = true))
                    }
                }
            } catch (e: Exception) {
                _errorMessage.value = e.message ?: "收藏操作失败"
            }
        }
    }
}